<?php
//TODO: refactor and doc this class.

class BaseDbService {
	
	private static $db_host;
	
	private static $db_name;

	private static $db_user;	
	
	private static $db_pass;
	
	private static function connect(){
		$link = mysql_connect(BaseDbService::$db_host, BaseDbService::$db_user, BaseDbService::$db_pass) or die ('Could not connect to database: ' . mysql_error());
		mysql_select_db(BaseDbService::$db_name, $link);
		mysql_query('SET NAMES utf8 COLLATE utf8_general_ci');
		return 	$link;
	}
	
	private static function close($link){
		mysql_close($link);
	}

	public static function init($host, $name, $user, $password){
		BaseDbService::$db_host = $host;
		BaseDbService::$db_name = $name;		
		BaseDbService::$db_user = $user;		
		BaseDbService::$db_pass = $password;		
	}

		public static function execute_select_query($query){	
		$result = array();
		$link = BaseDbService::connect(); 
		
		$res = mysql_query($query);
		if(!$res) {
	    	die('Error executing query: ' . mysql_error() . "\n" . 'Query: ' . $query);
		}
		
		while($row = mysql_fetch_assoc($res)) {
			array_push($result, $row);
		}
		//print_r($result);
		BaseDbService::close($link);
		return $result;
	}
	
	
	public static function get_count($table, $condition = null){
		$result = 0;
		
		$link = BaseDbService::connect();
		$query = "SELECT count(*) FROM $table";
		$query = $condition ?  "$query WHERE $condition" : $query;
		
		$res = mysql_query($query);
		if(!$res) {	die('Error executing query: ' . mysql_error() . "\n" . 'Query: ' . $query);	}
		$row = mysql_fetch_row($res);
		$result = $row[0]; 			

		BaseDbService::close($link);
		
		return $result;
	}

}
	
	
?>
